/*
dnf -y install gtest gtest-devel
g++ test_gtest_example.c -lgtest -lpthread
./a.out
*/
#include <gtest/gtest.h>

#ifdef HAVE_WEBKIT2GTK
#include <webkit2/webkit2.h>
#endif

extern "C"{
#include "spicy.h"
#include "../vcd-common-api/vcd-download.h"
#include "../vcd-common-api/vcd-common.h"
#include "../vcd-rdp/vcd-error.h"
#include "../vcd-rdp/vcd-rdp.h"
#include "../vcd-common-api/vcd-json-parser.h"
#include "vcd-common-api/vcd-conf/vcd-conf.h"
#include "vcd-common-api/vcd-topbar/vcd-topbar.h"
}

#ifdef WIN32
    /*
    CTRL_C_EVENT - 当用户按下了CTRL+C,或者由GenerateConsoleCtrlEvent API发出.
    CTRL_BREAK_EVENT - 用户按下CTRL+BREAK, 或者由GenerateConsoleCtrlEvent API发出.
    CTRL_CLOSE_EVENT - 当试图关闭控制台程序，系统发送关闭消息。
    CTRL_LOGOFF_EVENT - 用户退出时，但是不能决定是哪个用户.
    CTRL_SHUTDOWN_EVENT - 当系统被关闭时.*/
    BOOL WINAPI event_handler(DWORD event)
    {
        switch(event)
        {
        case CTRL_CLOSE_EVENT:
        case CTRL_C_EVENT:
            return TRUE;
        }
        return FALSE;
    }
#else
    void waitpidexit(int sig){
        switch (sig)
        {
            case SIGINT:
            break;
            case SIGCHLD:
            while(waitpid(-1,NULL,WNOHANG) > 0){
                //M_DEBUG("waitpidexit success\n");
            }
            break;
        }
    }
#endif

static void init_signal(){

#ifdef WIN32
    if( !SetConsoleCtrlHandler( event_handler, TRUE ) )
    {
        fprintf( stderr, "error setting event handler.\n" );
    }
#else
    signal(SIGCHLD,waitpidexit);
#endif
}



static gboolean net_callback(gpointer res){
    struct network_response* nr = (struct network_response*)res;
    char* p = (char*)nr->memory;
    return TRUE;
}


TEST(testCase, aes)
{
    //char* passwd = "123-com012345678901234567890123456789012345678901234567890";
    char* passwd = "012345678901234567890123456789012345678901234567890";
    int passwd_len = strlen(passwd);
    int aes_len = passwd_len;

    #if 1
    if(aes_len % 16)
        aes_len += ( 16 - (aes_len % 16));
    #endif

    char aes_encode_out[500] = {0};

    char tmp[1000] = {0};
    memcpy(tmp,passwd,passwd_len);
    aes_encrypt_extend(tmp,aes_len,aes_encode_out);

    char base64_encode_out[1024] = {0};
    base64_encode(aes_encode_out, aes_len, base64_encode_out);

    char base64_decode_out[200] = {0};
    base64_decode(base64_encode_out, strlen(base64_encode_out), base64_decode_out);

    char aes_decode_out[500] = {0};
    aes_decrypt_extend(base64_decode_out, 400, aes_decode_out);

    fprintf(stderr,"passwd_len:%d,aes_len:%d,succss:%d\n",passwd_len,aes_len,!strcmp(passwd,aes_decode_out));
    fprintf(stderr,"aes_decode_out:%s\n",aes_decode_out);

    EXPECT_EQ(0,0);
}

TEST(testCase, log4c)
{
    char* verystream = "C:\\Program Files (x86)\\verycloud\\VeryClient\\bin\\verystream.exe";

    spice_connect_data scd = {0};
    vcd_common_init_some_path(verystream,&scd);
    vcd_log_init_with_logdir(scd.log4crc_path,scd.log_dir);

    LOG_DEBUG("log debug");
    LOG_INFO("log info");
    LOG_ERROR("log error");

    EXPECT_EQ(0,0);
}


TEST(testCase, spice)
{
    gtk_init(0,0);

    const char* host = "192.168.199.162";
    const char* port = "61000";
    const char* pass = "123";
    const char* proxy = NULL;

#if __WIN32__
    //char* verystream = "C:\\msys32\\home\\feng\\freerdp\\build\\Debug\\wfreerdp.exe";
    char* verystream = "C:\\Program Files (x86)\\verycloud\\VeryClient\\bin\\verystream.exe";
#else
    char* verystream = "verystream";
#endif

    //init_signal();

    spice_connect_data scd = {0};

    //vcd_common_init_platform();

    //vcd_common_init_some_path(verystream,&scd);
    vcd_log_init_with_logdir("/etc/log4crc","/var/log");
    //const char* str = "{\"vmid\": 102, 	\"node\": \"v-d3mcboi1\", 	\"name\": \"test01\", 	\"host\": \"pvespiceproxy:5f0c0db8:102:v-d3mcboi1::18d8d3b1c92996108c7e550628a4ef20db79490c\", 	\"proxy\": \"http:\\/\\/192.168.50.251:65128\", 	\"port\": \"61002\", 	\"password\": \"f4f376084b9c6160de7fd9756dcebff3cd0b5408\", 	\"username\": \"feng@pve\", 	\"stream\": \"on\", 	\"protocol\": \"stream\", 	\"audio\": \"off\", 	\"usb\": \"off\", 	\"local_disk_redirect\": \"off\", 	\"gdi\": \"1\", 	\"image_quality\": \"20\", 	\"scale\": \"100\", 	\"windowsUsername\": \"Administrator\", 	\"windowsPassword\": \"123.com\", 	\"expires_in\": 1594625763, 	\"client_ip\": \"192.168.50.9\", 	\"gwdata\": \"192.168.50.32,23389,123456.com\", 	\"streamip\": \"192.168.50.251\", 	\"streamport\": \"65129\", 	\"api_port\": \"6300\" }";
    //spice_connect_data scd = {0};
    //vcd_json_parser_spice_connect_data(str,&scd);

//    spicy_connect_with_priv(host,port,pass,proxy,&scd);
    spicy_connect_with_priv(host,port,pass,proxy,0);

    gtk_main();
    EXPECT_EQ(0,0);
}

TEST(testCase, fakelogin)
{
#if __WIN32__
    //char* verystream = "C:\\msys32\\home\\feng\\freerdp\\build\\Debug\\wfreerdp.exe";
    char* verystream = "C:\\Program Files (x86)\\verycloud\\VeryClient\\bin\\verystream.exe";
#else
    char* verystream = "verystream";
#endif


    gtk_init(0,0);
    init_signal();

    spice_connect_data scd = {0};

    vcd_common_init_platform();
    start_download_thread(0);

    vcd_common_init_some_path(verystream,&scd);
    vcd_log_init_with_logdir(scd.log4crc_path,scd.log_dir);

    UINT32 exitCode = 0x10005;
    M_ERROR("parse exitcode name:%s  info:%s   category:%s",freerdp_get_last_error_name(exitCode),freerdp_get_last_error_string(exitCode),freerdp_get_last_error_category(exitCode));


    // use Vclient
    //setVcdClientFlg(TRUE);

    const char* host = "192.168.199.162";
    const char* port = "61000";
    const char* pass = "123";
    const char* proxy = NULL;

    scd.use_rdp = FALSE;
    sprintf(scd.rdp_host,"%s","192.168.199.216");
    sprintf(scd.rdp_port,"%s","3389");

    scd.use_guest_user_pass = TRUE;
    sprintf(scd.guest_name,"%s","root");
    sprintf(scd.guest_pass,"%s","123");

    scd.rdp_stream_path = verystream;
    scd.use_audio = FALSE;

#if 1
    spicy_connect_with_priv(host,port,pass,proxy,&scd);

    gtk_main();
#else
    vcd_rdp_start_sync(&scd);
#endif

    EXPECT_EQ(0,0);
}


TEST(testCase, test1)
{

    gtk_init(0,0);

    read_vcd_conf();
    vcd_rdp_start_sync(0);

    gtk_main();

    EXPECT_EQ(0,0);
}

TEST(testCase, topbar)
{

    gtk_init(0,0);

    VcdTopbarCtx* context = (VcdTopbarCtx*)g_malloc0(sizeof(VcdTopbarCtx));
    // test
    context->parent_winid = 0x009C0E62;
    //context->position = POSITION_LEFT;
    context->is_show_topbar = TRUE;
    vcd_topbar_new(context);

    gtk_main();

    EXPECT_EQ(0,0);
}

#ifdef HAVE_WEBKIT2GTK
gboolean _context_menu(WebKitWebView *web_view,WebKitContextMenu *context_menu,GdkEvent *event,WebKitHitTestResult *hit_test_result){
    return FALSE;
}

void _resource_load_started(WebKitWebView *web_view,WebKitWebResource *resource,WebKitURIRequest *request){

    // https://vdp.verycloud.cn/api/user/logout
    // Vclient://xxxx

    const char* pp = webkit_uri_request_get_uri(request);
    return;
}

TEST(testCase, webkit)
{

    gtk_init(0,0);

    GtkWidget* window = NULL;
    GtkWidget* webview  = NULL;
    GtkWidget* scrolled = NULL;

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    webview = webkit_web_view_new();
    scrolled = gtk_scrolled_window_new(NULL,NULL);

    gtk_window_set_default_size(GTK_WINDOW(window),600,400);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled),GTK_POLICY_AUTOMATIC,GTK_POLICY_AUTOMATIC);

    gtk_container_add(GTK_CONTAINER(scrolled),webview);
    gtk_container_add(GTK_CONTAINER(window),scrolled);

    //gtk_window_fullscreen(GTK_WINDOW(window));
    gtk_widget_show_all(window);

    WebKitSettings *webkitSettings = webkit_settings_new();
    webkit_settings_set_enable_fullscreen(webkitSettings, TRUE);
    webkit_settings_set_enable_javascript(webkitSettings, TRUE);
    webkit_settings_set_enable_webgl(webkitSettings, TRUE);
    webkit_settings_set_enable_plugins(webkitSettings, TRUE);
    webkit_settings_set_enable_developer_extras(webkitSettings, TRUE);
    webkit_web_view_set_settings(WEBKIT_WEB_VIEW(webview),webkitSettings);

    g_signal_connect(WEBKIT_WEB_VIEW(webview),"resource_load_started",G_CALLBACK(_resource_load_started),webview);
    g_signal_connect(WEBKIT_WEB_VIEW(webview),"context_menu",G_CALLBACK(_context_menu),webview);

    const char* url = "https://vdp.verycloud.cn/client";
    //const char* url = "file:///root/workspace/openVclient.html";

    WebKitWebContext* context = webkit_web_view_get_context(WEBKIT_WEB_VIEW(webview));
    WebKitCookieManager* cookie = webkit_web_context_get_cookie_manager(context);

    SoupCookie soupCookit = {0};
    soupCookit.name = "token";
    soupCookit.path = "/";
    soupCookit.value = "FV4kHWsMGVJdA5y_PUld=VO9Fxgnttq8ENApM7O_31Iqkm1apLNaAQhe8ptRCmQMDAMe3hV68";
    soupCookit.domain = "vdp.verycloud.cn";
    webkit_cookie_manager_add_cookie(cookie,&soupCookit,NULL,NULL,NULL);

    soupCookit = {0};
    soupCookit.name = "x-webview";
    soupCookit.path = "/";
    soupCookit.value = "1";
    soupCookit.domain = "vdp.verycloud.cn";
    webkit_cookie_manager_add_cookie(cookie,&soupCookit,NULL,NULL,NULL);

    webkit_web_view_load_uri(WEBKIT_WEB_VIEW(webview),url);

    //WebKitURIRequest* request = webkit_uri_request_new(url);
    //SoupMessageHeaders * header = webkit_uri_request_get_http_headers(request);
    //soup_message_headers_append(header,"Authorization","FV4kHWsMGVJdA5y_PUld=VO9Fxgnttq8ENApM7O_31Iqkm1apLNaAQhe8ptRCmQMDAMe3hV68");
    //soup_message_headers_append(header,"Origin","https://vdp.verycloud.cn");
    //soup_message_headers_append(header,"x-webview","123456");
    //webkit_web_view_load_request(WEBKIT_WEB_VIEW(webview),request);

    gtk_main();

    EXPECT_EQ(0,0);
}
#endif

int main(int argc, char* argv[])
{
 // --gtest_filter=testCase.fakelogin
 testing::InitGoogleTest(&argc, argv);
 return RUN_ALL_TESTS();
}
